<?php
namespace app\api\controller\v5;
use app\astro\controller\Data;
use \app\check\controller\Check;
use app\common\lib\exception\ApiException;
use app\common\model\Recode;

class Profection extends Check
{

    /**
     * @return \think\response\Json
     * @throws ApiException
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function get($tt=[])
    {
        $timeinfo=[];
        $datetime = htmlspecialchars(input('datetime'));
        $timeinfo['timezone'] = (int)(input('timezone'));
        $id = input('id/d', 0);

        if (isset($tt) && $tt)
        {
            $datetime = $tt['datetime'];
            $timeinfo['timezone'] = $tt['timezone'];
            $id = $tt['id'];
            $tid = $tt['tid'];
        }


        $time = strtotime($datetime);
        $timeinfo['year'] = date('Y',$time);
        $timeinfo['month'] = date('m',$time);
        $timeinfo['day'] = date('d',$time);
        $timeinfo['hour'] = date('H',$time);
        $timeinfo['minute'] = date('i',$time);

        $timeinfo['is_summer'] = isSummerTime($timeinfo['hour'],$timeinfo['minute'],0,
            $timeinfo['month'],$timeinfo['day'],$timeinfo['year']) ? 1 : 0;

        $Data = new Data();

        $map = ['id' => $id, 'uid' => $this->user['id']];

        $userinfo = (new Recode())->getRecode($map);

        $timestamp1 = $Data->deal_time($userinfo);

        $utdatenow = strftime("%d.%m.%Y", $timestamp1);
        $utnow = strftime("%H:%M:%S", $timestamp1);

        $longitude = ($userinfo['long_deg'] + $userinfo['long_min'] / 60 ) * $userinfo['ew'];
        $latitude = ($userinfo['lat_deg'] + $userinfo['lat_min'] / 60 ) * $userinfo['ns'];

        $timestamp2 = $Data->deal_time($timeinfo);

        $days_alive = ($timestamp2 - $timestamp1)/3600/24; // 总天数
        $years_alive = $days_alive / 365.2422;// 365.2422  365.2421990  365.25
        $months_alive = $this->getTheMonthAgo($timestamp1,$timestamp2);

        $Set = new Astroset();
        $astro_set = $Set->get(true,'profection',false,$tid);// 内部调用
        $Data->planets_display = $astro_set['value']['planets_display'];
        $Data->asps_display = $astro_set['value']['asps_display'];
        $Data->asp_orb_all = $astro_set['value']['asp_orb_all'];
        $Data->planet_orb_all = $astro_set['value']['planet_orb_all'];

        $options = ['utdatenow' => $utdatenow, 'utnow' => $utnow, 'longitude' => $longitude, 'latitude' => $latitude, 'h_sys' => $astro_set['value']['h_sys']];

        $out = $Data->execData($options);

        $original_data = $Data->getOriginalData($out,$astro_set['value']['h_sys']);
        $Data->array_remove($original_data,$Data->planets_display);
        $details = $Data->getPlanetHouseDetail($original_data, $original_data['hc1']);
        $phase = $Data->planetPkPlanet($original_data, $original_data, true);
        foreach ($phase['planets'] as $k => $d)
        {
            $details['planets'][$k]['phase'] = $d['phase'];
            if(empty($d['phase'])) $details['planets'][$k]['phase'] = null;
        }
        $details['phase'] = $phase['phase'];

        $profection_year = ceil($years_alive) % 12;
        $profection_month = ($months_alive) % 12;
        $profection_year = $profection_year === 0 ? 12 : $profection_year;
        $profection_month = $profection_month === 0 ? 12 : $profection_month;

        $time_use_year = $time_use_month =  $timestamp2 + $timeinfo['timezone'] * 3600 + $timeinfo['is_summer'] * 3600;

        $month_day = $userinfo['month'].'月'.$userinfo['day'].'日';

        $start_year = strtotime("-$profection_year year",$time_use_year);
        $start_month = strtotime($timeinfo['year'].'-'.$userinfo['month'].'-'.$userinfo['day']);
        $start_month = strtotime("+1 month",$start_month);
        $years_use = floor($years_alive) - ($profection_year - 1);
        // 12宫
        for($i = 1; $i < 13; $i++)
        {
            $end_year = strtotime("+1 year",$start_year);
            $end_month = strtotime("+1 month",$start_month);
            $details['profection']['details'][$i] = [
                'start_year'=>date("y年",$start_year).$month_day,
                'end_year'=>date("y年",$end_year).$month_day,
                'years_old_start'=>$years_use,
                'years_old_end'=>$years_use + 0.99,
                'start_month'=>date("y年m月d日",$start_month),
                'end_month'=>date("y年m月d日",$end_month),
            ];
            $start_year = $end_year;
            $start_month = $end_month;
            $years_use++;

        }

        $details['profection']['year_house'] = $profection_year;
        $details['profection']['month_house'] = $profection_month;

        $details['planets'] = (object)$details['planets'];// 指定输出为object  防止所有行星全开时 类型改变

        if (isset($tt) && $tt)
        {
            return $details;
        }else{
            return show(config('code.success'),'Success.',$details);
        }
    }

    /**
     * 计算两个时间戳相差月份数
     * @param null integer $time1 开始时间戳
     * @param null integer $time2 结束时间戳
     * @return int 相差月份数
     * @throws ApiException
     */
    private function getTheMonthAgo($time1=null,$time2=null)
    {
        if ($time2 < $time1)
        {
            throw new ApiException('当前选择时间早于出生时间');
//            echo json_encode(['code'=>10730,'msg'=>'Local time less than birth time.']);
//            exit;
        }
        $year1 = date("Y",$time1);
        $month1 = date("m",$time1);
        $day1 = date("d",$time1);
        $year2 = date("Y",$time2);
        $month2 = date("m",$time2);
        $day2 = date("d",$time2);

        if($day2 < $day1)
        {
            $month2--;
        }
        if($month2 < $month1)
        {
            $month2 += 12;
            $year2--;
        }
        $month = $month2- $month1 + ($year2 - $year1) * 12;
        return $month;
    }
}
